package com.yuqing.sentimentapp.update;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;

import com.linkface.baselibrary.utils.AppManager;
import com.linkface.baselibrary.utils.FileUtils;
import com.linkface.baselibrary.utils.LogUtil;
import com.linkface.baselibrary.utils.ThreadManager;
import com.yuqing.sentimentapp.BuildConfig;
import com.yuqing.sentimentapp.MainActivity;
import com.yuqing.sentimentapp.QYApplication;
import com.yuqing.sentimentapp.R;
import com.yuqing.sentimentapp.utils.InstallUtil;
import com.yuqing.sentimentapp.utils.NotificationsUtils;
import com.yuqing.sentimentapp.utils.UpdateAppManager;
import com.yuqing.sentimentapp.utils.download.DownloadUtil;

import java.io.File;

/**
 * Created by hqd on 2017/12/19.
 */

public class UpdateService extends Service {
    private String taskFilePath;
    private String downLoadUrl;
    private String name;
    private boolean isNotify;
    private int size;
    private Activity activity;

    //client 可以通过Binder获取Service实例
    public class MyBinder extends Binder {
        public UpdateService getService() {
            return UpdateService.this;
        }
    }

    //通过binder实现调用者client与Service之间的通信
    private MyBinder binder = new MyBinder();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    /**
     *
     * @param activity
     * 初始化MainActivity对象
     */
    public void setMainActivity(Activity activity)
    {
        this.activity = activity;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            taskFilePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
        }
        if (intent != null) {
            downLoadUrl = intent.getStringExtra("apkUrl");
            name = intent.getStringExtra("name");
            isNotify = intent.getBooleanExtra("isNotify", true);
            upadte();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void upadte() {
        DownloadUtil downloadUtil = new DownloadUtil(1, taskFilePath, name, downLoadUrl, QYApplication.getAppContext());
        downloadUtil.setOnDownloadListener(new DownloadUtil.OnDownloadListener() {
            private NotificationManager notificationManager;
            private Notification notification; //下载通知进度提示
            private NotificationCompat.Builder builder;
            int max;

            @Override
            public void downloadStart(int fileSize) {
                size = 0;
                UpdateAppManager.setIsDownLoad(true);
                max = fileSize;
                if (isNotify && NotificationsUtils.isNotificationEnabled(QYApplication.getAppContext())) {
                    notificationManager = (NotificationManager) QYApplication.getAppContext().getSystemService(Context.NOTIFICATION_SERVICE);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        CharSequence name = QYApplication.getAppContext().getString(R.string.app_name);
                        NotificationChannel channel = new NotificationChannel(QYApplication.getAppContext().getApplicationContext().getPackageName(), name, NotificationManager.IMPORTANCE_DEFAULT);
                        channel.setSound(null, null);
                        notificationManager.createNotificationChannel(channel);
                    }
                    builder = new NotificationCompat.Builder(QYApplication.getAppContext(), QYApplication.getAppContext().getApplicationContext().getPackageName());
                    builder.setContentTitle("正在更新...") //设置通知标题
                            .setSmallIcon(R.drawable.ic_logo) //设置通知的小图标
                            .setLargeIcon(BitmapFactory
                                    .decodeResource(QYApplication.getAppContext().getResources(),
                                            R.drawable.ic_logo)) //设置通知的大图标
                            .setDefaults(Notification.DEFAULT_LIGHTS) //设置通知的提醒方式： 呼吸灯
                            .setPriority(NotificationCompat.PRIORITY_MAX) //设置通知的优先级：最大
                            .setOnlyAlertOnce(true)
                            .setAutoCancel(false)//设置通知被点击一次是否自动取消
                            .setContentText("下载进度:" + "0%")
                            .setProgress(100, 0, false);
                    notification = builder.build();//构建通知对象
                }
            }

            @Override
            public void downloadProgress(int downloadedSize) {
                if (size != downloadedSize * 100 / max) {
                    size = downloadedSize * 100 / max;
                    if (isNotify && NotificationsUtils.isNotificationEnabled(QYApplication.getAppContext())) {
                        ThreadManager.getThreadPollProxy().execute(new Runnable() {
                            @Override
                            public void run() {
                                if (size == 100) {
                                    builder.setContentTitle("下载完成");
                                }
                                builder.setProgress(100, size, false);
                                builder.setContentText("下载进度:" + size + "%");
                                notification = builder.build();
                                notificationManager.notify(1, notification);
                            }
                        });
                    }
                }
            }

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void downloadEnd() {
                UpdateAppManager.setIsDownLoad(false);
                if (isNotify) {
                    File file = new File(taskFilePath + "/" + name);
                    if (file.exists()) {
                        boolean isGranted = activity.getPackageManager().canRequestPackageInstalls();
                        new InstallUtil(activity, file.getAbsolutePath()).install();
                        if (!isGranted) {
                            //安装权限被禁止 则通知栏提示点击安装
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            Uri apkUri = FileProvider.getUriForFile(getBaseContext(), BuildConfig.APPLICATION_ID + ".fileprovider", new File(file.getAbsolutePath()));
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            //添加这一句表示对目标应用临时授权该Uri所代表的文件
                            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                            PendingIntent pi = PendingIntent.getActivity(activity, 0, intent, 0);
                            notification = builder.setContentIntent(pi)
                                    .setContentText("下载完成")
                                    .setProgress(0, 0, false)
                                    .build();
                            notificationManager.notify(1, notification);
                        }
                    }
                }
            }
        });
        downloadUtil.start();
    }
}
